package com.gzhryc.socket.mosquitto.log;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.gzhryc.common.logging.Logger;
import com.gzhryc.socket.SocketCallback;
import com.gzhryc.socket.SocketEvent;
import com.gzhryc.socket.SocketNode;
import com.gzhryc.socket.mosquitto.EmptyMqttNode;

public class ClientConnectedLogHandler extends MosquittoLogHandler{
	
	static Logger log = Logger.getLogger(ClientConnectedLogHandler.class);
	
	Pattern part = Pattern.compile("New client connected from (.*) as (.*) \\((.*),(.*).*\\)");

	public ClientConnectedLogHandler(MosquittoLogHandler nextHandler,SocketNode node,SocketCallback callback) {
		super(nextHandler,node,callback);
	}

	@Override
	public boolean execute(String logStr) {
		Matcher mat = part.matcher(logStr);
		if(mat.find()){
			String ipAddress = mat.group(1);
			String clientId = mat.group(2);
			log.debug("ClientId:"+clientId+",IP:"+ipAddress+" connected!!!");
			final SocketEvent event = new SocketEvent(new EmptyMqttNode(clientId,ipAddress,null));
			event.getSocketNode().setConnectedDate(new Date());
			mNode.runTask(new Runnable() {
				@Override
				public void run() {
					mCallback.connected(event);
				}
			});
			return true;
		}
		return super.execute(logStr);
	}

}
